package cn.com.yusys.yusp.admin.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;

import cn.com.yusys.yusp.admin.domain.AdminSmDpt;
import cn.com.yusys.yusp.admin.domain.AdminSmUser;
import cn.com.yusys.yusp.admin.repository.mapper.AdminSmDptMapper;
import cn.com.yusys.yusp.commons.exception.MessageConstants;
import cn.com.yusys.yusp.commons.mapper.CommonMapper;
import cn.com.yusys.yusp.commons.mapper.QueryModel;
import cn.com.yusys.yusp.commons.service.CommonService;
import cn.com.yusys.yusp.commons.util.DateUtil;
import cn.com.yusys.yusp.commons.web.rest.dto.ResultDto;

/**
 * @version 1.0.0
 * @项目名称: yusp-admin
 * @类名称: AdminSmDptService
 * @类描述:
 * @功能描述: 部门管理
 * @创建人: chenlin2@yusys.com.cn
 * @创建时间: 2017年12月27日
 * @修改备注:
 * @修改记录: 修改时间    修改人员    修改原因
 * -------------------------------------------------------------
 * @Copyright (c) 2017宇信科技-版权所有
 */
@Service
public class AdminSmDptService extends CommonService {
    private Logger logger = LoggerFactory.getLogger(AdminSmDptService.class);
    @Autowired
    private AdminSmDptMapper mapper;

    public AdminSmDptService(AdminSmDptMapper commonMapper) {
        super();
        this.mapper = commonMapper;
    }

    @Override
    protected CommonMapper<?> getMapper() {
        return this.mapper;
    }

    /**
     * @方法名称: getDptByModel
     * @方法描述: 部门查询
     * @参数与返回说明:
     * @算法描述:
     */
    public List<AdminSmDpt> getDptByModel(QueryModel model) {
        PageHelper.startPage(model.getPage(), model.getSize());

        if (model.getCondition().containsKey("dptName")) {
            if (model.getCondition().get("dptName") != null && !model.getCondition().get("dptName").equals("")) {
                model.getCondition().put("dptName", "%" + model.getCondition().get("dptName") + "%");
            }
        }

        List<AdminSmDpt> list = mapper.getDptByModel(model);
        PageHelper.clearPage();
        return list;
    }

    /**
     * @方法名称: getUserListByModel
     * @方法描述: 部门用户查询
     * @参数与返回说明:
     * @算法描述:
     */
    public List<AdminSmUser> getUserListByModel(QueryModel model) {
        PageHelper.startPage(model.getPage(), model.getSize());
        List<AdminSmUser> list = mapper.getUserListByModel(model);
        PageHelper.clearPage();
        return list;
    }

    /**
     * 新增部门
     */
    public int insertDpt(AdminSmDpt adminSmDpt) {
        adminSmDpt.setLastChgDt(DateUtil.formatDateTimeByDef());//最近更新时间
        adminSmDpt.setDptId(adminSmDpt.getDptCde());
        logger.info("New department data: [new department: {}] ", adminSmDpt.getDptName());
        return this.insertSelective(getMapper(), adminSmDpt);
    }

    /**
     * 修改部门
     */
    public int update(Object t) {
        AdminSmDpt pool = (AdminSmDpt) t;
        pool.setLastChgDt(DateUtil.formatDateTimeByDef());//最近跟新时间
        logger.info("Department modification data: related data of [modify department: {}]; " , pool.getDptName());
        return this.update(getMapper(), pool);
    }

    /**
     * @方法名称: deleteBatch
     * @方法描述: 批量删除部门
     * @参数与返回说明:
     * @算法描述:
     */
    @Transactional(readOnly = false, rollbackFor = {Exception.class, RuntimeException.class})
    public ResultDto<Object> deleteBatch(String[] idStr) {
        int n = 0;
        List<Object> i18nData = new ArrayList<Object>();
        ResultDto<Object> resultDto = new ResultDto<Object>();
        if (idStr != null && !"".equals(idStr.toString())) {
            int undeletes = 0;
            int undeletes1 = 0;
            for (int i = 0; i < idStr.length; i++) {
                if (!"".equals(idStr[i])) {
                    int userNum = this.mapper.checkHasUser(idStr[i]);
                    int nodeNum = this.mapper.checkHasNode(idStr[i]);
                    if (userNum > 0) {
                        undeletes++;
                    } else if (nodeNum > 0) {
                        undeletes1++;
                    } else {
                        n = n + mapper.deleteByPrimaryKey(idStr[i]);
                    }
                }
            }
            if (undeletes == 0 && undeletes1 == 0) {
//                result.put("message", "成功删除" + n + "条数据!");
            	
            	resultDto.setCode(0);
            	resultDto.setMessage("成功删除" + n + "条数据!");
            	i18nData.add(n);
            } else if (undeletes == 0 && undeletes1 != 0) {
//                result.put("message", "成功删除" + n + "条数据,有" + undeletes1 + "条数据由于存在下级部门，无法删除!");
                resultDto.setCode(0);
                resultDto.setMessage("成功删除" + n + "条数据,有" + undeletes1 + "条数据由于存在下级部门，无法删除!");
                i18nData.add(n);
                i18nData.add(undeletes1);
            } else if (undeletes != 0 && undeletes1 == 0) {
//                result.put("message", "成功删除" + n + "条数据,有" + undeletes + "条数据由于存在用户，无法删除!");
                resultDto.setCode(0);
                resultDto.setMessage("成功删除" + n + "条数据,有" + undeletes + "条数据由于存在用户，无法删除!");
                i18nData.add(n);
                i18nData.add(undeletes);
            } else {
//                result.put("message", "成功删除" + n + "条数据,有" + (undeletes + undeletes1) + "条数据由于存在用户和下级部门，无法删除!");
                resultDto.setCode(0);
                resultDto.setMessage("成功删除" + n + "条数据,有" + (undeletes + undeletes1) + "条数据由于存在用户和下级部门，无法删除!");
                i18nData.add(n);
                i18nData.add(undeletes + undeletes1);
            }
        }
        resultDto.setI18nData(i18nData);
        return resultDto;
    }

    /**
     * @方法名称: useIngFn
     * @方法描述: 批量启用部门
     * @参数与返回说明:
     * @算法描述:
     */
    public int useIngFn(String[] idStr, String userId) {
        int n = 0;
        //modify by Cytus_ at 20180904 修改sonar扫描出现的bug， !"".equals(idStr.toString())语句无意义，根据上下文修改为idStr.length > 0
        if (idStr != null && /*!"".equals(idStr.toString())*/idStr.length > 0) {
            for (int i = 0; i < idStr.length; i++) {
                if (!"".equals(idStr[i])) {
                    Map<String, String> paramMap = new HashMap<String, String>();
                    paramMap.put("dptId", idStr[i]);
                    paramMap.put("dptSts", "A");
                    paramMap.put("lastChgUsr", userId);
                    paramMap.put("lastChgDt", DateUtil.formatDateTimeByDef());
                    n = n + this.mapper.updateSts(paramMap);
                }
            }
            logger.info("Department batch enable [primary key: {}] " ,new Object[] {idStr});
        }
        return n;
    }

    /**
     * @方法名称: unUseIngFn
     * @方法描述: 批量停用部门
     * @参数与返回说明:
     * @算法描述:
     */
    public ResultDto<Object> unUseIngFn(String[] idStr, String userId) {
        int n = 0;
        ResultDto<Object> resultDto = new ResultDto<Object>();
        List<Object> i18nData = new ArrayList<Object>();
        //modify by Cytus_ at 20180904 修改sonar扫描出现的bug， !"".equals(idStr.toString())语句无意义，根据上下文修改为idStr.length > 0
        if (idStr != null && /*!"".equals(idStr.toString())*/idStr.length > 0) {
            int unUse = 0;
            int unUse1 = 0;
            for (int i = 0; i < idStr.length; i++) {
                if (!"".equals(idStr[i])) {
                    int userNum = this.mapper.checkHasUser(idStr[i]);
                    int nodeNum = this.mapper.checkHasNode(idStr[i]);
                    if (userNum > 0) {
                        unUse++;
                    } else if (nodeNum > 0) {
                        unUse1++;
                    } else {
                        Map<String, String> paramMap = new HashMap<String, String>();
                        paramMap.put("dptId", idStr[i]);
                        paramMap.put("dptSts", "I");
                        paramMap.put("lastChgUsr", userId);
                        paramMap.put("lastChgDt", DateUtil.formatDateTimeByDef());
                        n = n + this.mapper.updateSts(paramMap);
                        logger.info("Department disabled [primary key: {}] ", idStr[i]);
                    }
                }

            }
            if (unUse == 0 && unUse1 == 0) {
//                result.put("message", "成功停用" + n + "条数据!");
            	resultDto.setCode(0);
            	resultDto.setMessage("成功停用" + n + "条数据!");
            	i18nData.add(n);
            } else if (unUse == 0 && unUse1 != 0) {
//                result.put("message", "成功停用" + n + "条数据,有" + unUse1 + "条数据由于存在下级部门，无法停用!");
                resultDto.setCode(0);
                resultDto.setMessage("成功停用" + n + "条数据,有" + unUse1 + "条数据由于存在下级部门，无法停用!");
                i18nData.add(n);
                i18nData.add(unUse1);
            } else if (unUse != 0 && unUse1 == 0) {
//                result.put("message", "成功停用" + n + "条数据,有" + unUse + "条数据由于存在用户，无法停用!");
                resultDto.setCode(0);
                resultDto.setMessage("成功停用" + n + "条数据,有" + unUse + "条数据由于存在用户，无法停用!");
                i18nData.add(n);
                i18nData.add(unUse);
            } else {
//                result.put("message", "成功停用" + n + "条数据,有" + (unUse + unUse1) + "条数据由于存在用户和下级部门，无法停用!");
                resultDto.setCode(0);
                resultDto.setMessage("成功停用" + n + "条数据,有" + (unUse + unUse1) + "条数据由于存在用户和下级部门，无法停用!");
                i18nData.add(n);
                i18nData.add(unUse + unUse1);
            }
        }
        resultDto.setI18nData(i18nData);
        return resultDto;
    }

    /**
     * @方法名称: checkCode
     * @方法描述: 检查部门编号是否重复
     * @参数与返回说明:
     * @算法描述:
     */
    public int checkDptCode(String dptCde) {
        return this.mapper.checkDptCode(dptCde);
    }
}
